import React, { useEffect, useRef } from 'react'
import * as echarts from 'echarts'
import { Empty, Spin } from 'antd'
import { EChartsType } from 'echarts'

// 给props添加类型检查
export interface IProps {
  loading: boolean // 加载标识
  title?: string // 图表的标题（为string类型）
  xData: string[] // 图表x轴数据的数组（数字里面每一项都为string类型）
  seriesData: number[] // 跟x轴每个坐标点对应的数据（数字里面每一项都为number类型）
  width?: number // 图表宽度
  height?: number // 图表高度
}

const LineChart: React.FC<IProps> = (props) => {
  const { loading, title, xData, seriesData, width = 600, height = 300 } = props
  const chartRef: any = useRef() // 拿到DOM容器
  let myChart: EChartsType

  // 每当props改变的时候就会实时重新渲染
  useEffect(() => {
    if (chartRef.current) {
      initChart()
    }

    return () => {
      myChart && myChart.dispose()
    }
  }, [props])

  /**
   * 初始化Echarts
   */
  const initChart = () => {
    const chart = echarts.getInstanceByDom(chartRef.current) // echart初始化容器
    myChart = chart || echarts.init(chartRef.current)

    const option = {
      // 配置项(数据都来自于props)
      title: {
        text: title || '',
      },
      xAxis: {
        type: 'category',
        data: xData,
      },
      yAxis: {
        type: 'value',
      },
      tooltip: {
        trigger: 'axis',
      },
      series: [
        {
          data: seriesData,
          type: 'line',
        },
      ],
    }

    myChart.setOption(option)

    window.onresize = () => {
      myChart.resize()
    }
  }

  return (
    <Spin spinning={loading}>
      {xData?.length && seriesData?.length ? (
        <div ref={chartRef} style={{ width, height, margin: '0 auto' }} />
      ) : (
        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
      )}
    </Spin>
  )
}

export default LineChart
